.NET 泛型入门简介

泛型可以简单的理解为:在类名后面后,添加用<>尖括号括起来的类型参数列表,用来定义一组“通用化”的类型

class Pair<T1,T2>
{
    public T1 First;
    public T2 Second;
}

以上Pair类的类型参数为T1,T2。T1,T2可以代表任何类型,因此只需要定义一次泛型就可以实现所有参数类型的调用。

以下为Pair类的应用实例

 Pair<int,stirng> p=new  Pair<int,stirng>
{
    First=1;
    Second=2;
}
......

int i=p.First;
string s=p.Second;

在定义泛型类型时可以对客户端代码在实例化类时用于类型参数的类型加以限制,
  • 使用Where关键字指定
  • 多个限制,使用应为”,”分开
  • new() 放到最后































    约束说明
    where T: struct类型参数必须是值类型
    where T: class类型参数必须是引用类型
    where T: new()类型参数必须有一个 public 且无参数的构造函数
    where T: <base classname>类型参数必须继承至指定的基类(base class)
    where T: <interface name>类型参数必须是指定的接口或实现了指定接口的类型
    where T: U为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数
 class Pair&lt;T1,T2&gt;  where T : class, new()
{
    public T1 First;
    public T2 Second;
}

以上限制,类型参数为

  • 参数必须是引用类型
  • 参数必有一个public且无参数的构造函数
  • [TestMethod] 
    public void TestMethod1() 
    { 
        List&lt;String&gt; names = ``new` `List&lt;String&gt;();`</div>
        names.Add( "Bruce" ); 
        names.Add( "Alfred" ); 
        names.Add( "Tim" ); 
        names.Add( "Richard" ); 
    
    names.ForEach(Print); 
    }
    
    private void Print( string s) 
    {
        Console.WriteLine(s);`</div>
    }
    
    常用的泛型有
  • List<T>列表

  • LinkedList<T>链表
  • Dictionary<TKey,TValue>字典
  • Queue<T>队列
  • Stack<T>堆栈
    参考:http://www.cnblogs.com/forgetu/archive/2011/05/08/csharp-generics.html

Blog.jobbole.com/87980

文章目录
|